const fs = require("fs");
const http = require("http");

http.createServer((request, response) => {
    // console.log("a request", getPrototypeChain(request), getPrototypeChain(response));
    // response.end("Hi World"); // 这个end不太好，不好理解
    // TODO? response和request 都是流

    const {url, method, headers} = request;
    console.log("url:", url);
    if (url === "/" && method === "GET") {
        fs.readFile("index.html", (err, data) => {
            if (err) {
                response.writeHead(500, {
                    "Content-Type": "text/plian;charset=utf-8",
                });
                response.end("500 服务器挂了！！！");
            }
            response.statusCode = 200;
            response.setHeader("Content-Typr", "text/html");
            response.end(data);
        });
    } else if (url === "/users1" && method === "GET") {
        response.writeHead(200, {"Content-Type": "application/json"});
        response.end(JSON.stringify({name: "yk菌"}));
    } else if (method === "GET" && headers.accept.indexOf("image/*" !== -1)) {
        // 拿到所有图片
        // 直接使用readFile读取 不行， 因为它要把全部图片内容加载到服务器
        // 使用 流 stream ！！！！
        fs.createReadStream("." + url.pipe(request));
    } else {
        response.statusCode = 400;
        response.setHeader("Content-Type", "text/plain;charste=utf-8");
        response.end("404 找不到了呀！");
    }
}).listen(3000, () => {
    console.log("Server at 3000");
});

function getPrototypeChain(obj) {
    const protoChain = [];
    while ((obj = Object.getPrototypeOf(obj))) {
        protoChain.push(obj);
    }
    return protoChain;
}
